import utils.TreeNode;

/**
 * @author ZCR
 * @create 2025/9/7 08:12
 */
public class Solution297 {
    public class Codec {
        int index = 0;

        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            StringBuilder sb = new StringBuilder();
            preorderTraversal(root, sb);
            return sb.toString();
        }

        public void preorderTraversal(TreeNode root, StringBuilder stringBuilder) {
            if (root == null) {
                stringBuilder.append("#,");
                return;
            }
            stringBuilder.append(root.val).append(",");
            preorderTraversal(root.left, stringBuilder);
            preorderTraversal(root.right, stringBuilder);

        }

        public TreeNode buildTree(String[] data) {
            if (index > data.length - 1) {
                return null;
            }
            if (data[index].equals("#")) {
                return null;
            }
            TreeNode root = new TreeNode(Integer.parseInt(data[index]));
            index++;
            root.left = buildTree(data);
            index++;
            root.right = buildTree(data);
            return root;
        }

        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            String[] str = data.split(",");

            return buildTree(str);
        }
    }

    public static void main(String[] args) {
        Solution297 solution = new Solution297();
        Solution297.Codec codec = solution.new Codec();
        TreeNode root = TreeNode.buildTree(new int[]{1, 2, 3, -1, -1, 4, 5}, -1);
        String data = codec.serialize(root);
        System.out.println(data);
        TreeNode newRoot = codec.deserialize(data);
        TreeNode.show(newRoot);
    }
}
